import React, {
    PureComponent
} from "react";
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Button,
    ScrollView,
    Image,
    Dimensions,
    TouchableOpacity, DeviceEventEmitter
} from "react-native";
import color from "../../widget/color";
import {
    ImageButton
} from '../../widget/CustomButton'
import RefreshListView, {
    RefreshState
} from "react-native-refresh-list-view";
import CourseAllCell from '../../widget/course/CourseAllCell'
import EmptyCouponView from "../../widget/CommonEmptyView";
import api from '../../api/api'
import method from '../../api/method'
import NetTool from '../../api/NetTool'
import Tips from "react-native-root-tips";
import DeviceStorage from "../../utils/DeviceStorage";
import define from "../../utils/define";
const {
    width
} = Dimensions.get('window')
const {height} = Dimensions.get('window')
type Props = {
    navigation: any,
}

type State = {
    data: Array < Object >,
    refreshState: number,
}

export default class CourseScene extends PureComponent < Props, State > {

    static navigationOptions = ({
        navigation
    }: any) => ({

        headerTintColor: 'white',
        title: '我的课程',
        headerStyle: {
            backgroundColor: color.globalMainColor
        },
        headerLeft: <View></View>,
        headerRight: <ImageButton onPress={()=>{
            DeviceStorage.get(define.token)
                .then(res=>{
                    if (res){
                        navigation.navigate('calendarSecene')
                     }else {
                        Tips.showWarn('请先登录',{mask:true})
                    }
                }).catch(err=>{
            })
        }} style={{marginRight:12}} source={require('../../../res/img/select/select_rili_icon.png')}/>
    })

    constructor(props) {
        super(props)
        this.state = {
            data: [],
            refreshState: RefreshState.Idle,
        }
    }

    componentDidMount() {
        DeviceEventEmitter.addListener('loginToken', (args) => {
            this.requestFirstPage()
        });
        DeviceEventEmitter.addListener('loginOut', () => {
            DeviceStorage.get(define.token)
                .then(res => {
                    if (res) {
                        this.setState({data: []})
                    } else {
                        Tips.showWarn('请先登录', {mask: true})
                    }
                }).catch(err => {
            })
        });
        DeviceStorage.get(define.token)
            .then(res => {
                if (res) {
                    this.requestFirstPage()
                } else {
                    Tips.showWarn('请先登录', {mask: true})
                }
            }).catch(err => {
        })
    }

    requestData = async() => {
        let json = await NetTool.fetchGetRequest(api.getUserCourseList, method.get,)

        return json.courses.map((info) => {
            return {
                id: info.id,
                title: info.title,
                start_date: info.start_date,
                end_date: info.end_date,
                zhu_teacher: info.teachers[0],
                fu_teacher: info.teachers[1],
                tag: info.tag,
                subject: info.subject,
            }
        })

    }

    requestFirstPage = async() => {

        try {
            this.setState({
                refreshState: RefreshState.HeaderRefreshing
            })
            let dataList = await this.requestData()

            this.setState({
                data: dataList,
                refreshState: RefreshState.Idle,
            })
        } catch (error) {
            this.setState({
                refreshState: RefreshState.Failure,
            })
        }
    }
    requestNextPage = async() => {

    }
    //custon ui
    keyExtractor = (item: Object, index: number) => {
        return index + ''
    }
    renderCell = (rowData: any) => {
        return (
            <CourseAllCell info={rowData.item} navigation={this.props.navigation}/>
        )
    }

    render() {

        return (
            <View style={styles.container}>
                <View style={{height:56,backgroundColor:'#F9F9F9',justifyContent:'center',}}>
                    <Text style={{marginLeft:12,color:'rgba(0,0,0,0.8)',fontSize:16,fontWeight:'bold'}}>全部课程</Text>
                </View>

                <RefreshListView
                    ListHeaderComponent={() => (
                    !this.state.data.length?
                    <EmptyCouponView height={(height-200)} tip={'没有找到相关课程信息'} source={require('../../../res/img/select/kecheng.png')}/>
                     : null)
                    }
                    data={this.state.data}
                    renderItem={this.renderCell}
                    keyExtractor={this.keyExtractor}
                    refreshState={this.state.refreshState}
                    onHeaderRefresh={this.requestFirstPage}
                    onFooterRefresh={this.requestNextPage}
                    ItemSeparatorComponent={()=><View style={{width:width,height:10,backgroundColor:'#F9F9F9'}}/>}
                />

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
        width: width,
    },
});